# -*- coding : utf-8 -*-
import os

import sys
import json
import datetime
sys.path.append('../../')
from flask import Flask, render_template, request, Response, make_response, stream_with_context
from flask_cors import CORS

from bot.financial_sales_b.sales import Sales
# import config
import asyncio


session_id_dict = dict()


os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"

arg = sys.argv
app = Flask(__name__)
CORS(app, resources=r'/*')
app.static_folder = 'static'


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/init')
def init():
    user_id = request.args.get('userId')
    init_scene = request.args.get('initScene')

    return '请在用户回复中输入"开始"，用户信息中输入用户信息。开始对话'

@app.route('/message')
def message():
    message = request.args.get('message')
    user_id = request.args.get('userId')
    user_info = request.args.get('userInfo')

    print(message)
    print(user_id)
    print(user_info)
    print(type(user_info))
    user_info = eval(user_info)

    # 判定最终需要使用的session Id
    if 'session_id' in user_info:
        session_id = user_info['session_id']
        user_id = session_id

    if user_id not in session_id_dict:
        session_id_dict[user_id] = list()
    if message != '开始':
        conversation_dict = {}
        conversation_dict["role"] = "user"
        conversation_dict["content"] = message
        query_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        conversation_dict["query_time"] = query_time
        session_id_dict[user_id].append(conversation_dict)

    sales = Sales('financial_loan_7b_b')
    reply_result = asyncio.run(sales.async_reply(session_id_dict[user_id], user_id, user_info))
    result = reply_result['reply_text']
    voice_record = reply_result.get('voice_record', '')
    conversation_prompt = reply_result['conversation_prompt']
    user_question = reply_result['user_question']
    user_question_prompt = reply_result['user_question_prompt']
    sales_skill = reply_result['sales_skill_name']
    sales_skill_prompt = reply_result['sales_skill_name_prompt']
    user_situation = reply_result['user_situation']
    user_situation_prompt = reply_result['user_situation_prompt']

    skill_knowledge = reply_result['skill_knowledge']
    solution_knowledge = reply_result['solution_knowledge']
    conversation_dict = {}
    conversation_dict["role"] = "assistant"
    conversation_dict["content"] = result
    query_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    conversation_dict["query_time"] = query_time
    conversation_dict["user_question"] = reply_result['user_question']
    conversation_dict["sales_skill_name"] = reply_result['sales_skill_name']
    conversation_dict["user_situation"] = user_situation
    conversation_dict["skill_knowledge"] = skill_knowledge
    conversation_dict["solution_knowledge"] = solution_knowledge


    session_id_dict[user_id].append(conversation_dict)


    return json.dumps({
        'sessionId': user_id,
        'user_question': user_question,
        'user_question_prompt': user_question_prompt.replace('\n', '<br>'),
        'sales_skill': sales_skill,
        'sales_skill_prompt': sales_skill_prompt.replace('\n', '<br>'),
        'user_situation': str(user_situation),
        'user_situation_prompt': user_situation_prompt.replace('\n', '<br>'),
        'context': result,
        'wav_no': voice_record,
        'conversation_prompt': conversation_prompt.replace('\n', '<br>')
    })


if __name__ == '__main__':

    # config.load_config()
    app.run(host='0.0.0.0', port=8072)



